package com.evan.review.anr;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.evan.review.R;

/**
 * 输入事件分发超时ANR示例Activity
 * 演示输入事件处理超时导致的ANR
 */
public class InputDispatchTimeoutActivity extends AppCompatActivity {

    private static final String TAG = "InputDispatchTimeoutANR";
    
    private Button btnBlockTouch; // 阻塞触摸事件按钮
    private Button btnBlockKey; // 阻塞按键事件按钮
    private View touchBlockArea; // 触摸阻塞区域
    private TextView tvLogger; // 日志文本框
    private ScrollView svLogger; // 日志滚动视图
    
    // 标记是否应该阻塞触摸事件
    private boolean shouldBlockTouch = false;
    private boolean shouldBlockKey = false;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_input_dispatch_timeout);
        
        initViews(); // 初始化视图
        setListeners(); // 设置监听器
        
        logMessage("提示：点击按钮将启用触摸事件阻塞，然后在灰色区域触摸将引发ANR");
        logMessage("输入事件ANR时间阈值：5秒");
    }
    
    /**
     * 初始化视图组件
     */
    private void initViews() {
        btnBlockTouch = findViewById(R.id.btn_block_touch);
        btnBlockKey = findViewById(R.id.btn_block_key);
        touchBlockArea = findViewById(R.id.touch_block_area);
        tvLogger = findViewById(R.id.tv_logger);
        svLogger = findViewById(R.id.sv_logger);
    }
    
    /**
     * 设置监听器
     */
    private void setListeners() {
        btnBlockTouch.setOnClickListener(v -> {
            shouldBlockTouch = !shouldBlockTouch;
            btnBlockTouch.setText(shouldBlockTouch ? "取消触摸阻塞" : "启用触摸阻塞");
            logMessage(shouldBlockTouch ? 
                    "触摸阻塞已启用，在灰色区域触摸将阻塞主线程6秒" : 
                    "触摸阻塞已取消，触摸将正常响应");
        });
        
        btnBlockKey.setOnClickListener(v -> {
            shouldBlockKey = !shouldBlockKey;
            btnBlockKey.setText(shouldBlockKey ? "取消按键阻塞" : "启用按键阻塞");
            logMessage(shouldBlockKey ? 
                    "按键阻塞已启用，按下返回键将阻塞主线程6秒" : 
                    "按键阻塞已取消，按键将正常响应");
        });
        
        // 设置触摸区域的触摸监听
        touchBlockArea.setOnTouchListener((v, event) -> {
            if (shouldBlockTouch && event.getAction() == MotionEvent.ACTION_DOWN) {
                logMessage("检测到触摸事件，开始阻塞主线程6秒...");
                // 阻塞主线程6秒，超过输入事件ANR阈值(5秒)
                SystemClock.sleep(6000);
                logMessage("主线程阻塞结束，如果看到此消息，说明ANR对话框被忽略或等待");
            }
            return true;
        });
    }
    
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // 监听返回键按下事件
        if (shouldBlockKey && event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            logMessage("检测到返回键按下，开始阻塞主线程6秒...");
            // 阻塞主线程6秒，超过输入事件ANR阈值(5秒)
            SystemClock.sleep(6000);
            logMessage("主线程阻塞结束，如果看到此消息，说明ANR对话框被忽略或等待");
            return true;
        }
        return super.dispatchKeyEvent(event);
    }
    
    /**
     * 记录日志信息到界面
     */
    private void logMessage(String message) {
        Log.d(TAG, message);
        
        new Handler(Looper.getMainLooper()).post(() -> {
            String currentText = tvLogger.getText().toString();
            String newText = currentText + "\n" + message;
            tvLogger.setText(newText);
            
            // 滚动到底部
            svLogger.post(() -> svLogger.fullScroll(View.FOCUS_DOWN));
        });
    }
} 